<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>python05-字典和集合 | 莫伊の测试笔记</title><meta name="keywords" content="Python"><meta name="author" content="莫伊"><meta name="copyright" content="莫伊"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="概念 字典dict：由一系列键（key）和值（value）配对组成的元素的集合 集合set：没有键和值的配对，是一系列无序的、唯一的元素组合创建方式  123456d1 &#x3D; &amp;#123;&amp;#x27;name&amp;#x27;: &amp;#x27;jason&amp;#x27;, &amp;#x27;age&amp;#x27;: 20, &amp;#x27;gender&amp;#x27;: &amp;#x27;male&amp;#x27;&amp;#125;d2 &#x3D; di">
<meta property="og:type" content="article">
<meta property="og:title" content="python05-字典和集合">
<meta property="og:url" content="https://mooii.gitee.io/2022/05/25/python05/index.html">
<meta property="og:site_name" content="莫伊の测试笔记">
<meta property="og:description" content="概念 字典dict：由一系列键（key）和值（value）配对组成的元素的集合 集合set：没有键和值的配对，是一系列无序的、唯一的元素组合创建方式  123456d1 &#x3D; &amp;#123;&amp;#x27;name&amp;#x27;: &amp;#x27;jason&amp;#x27;, &amp;#x27;age&amp;#x27;: 20, &amp;#x27;gender&amp;#x27;: &amp;#x27;male&amp;#x27;&amp;#125;d2 &#x3D; di">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://mooii.oss-cn-shanghai.aliyuncs.com/IMG_5370(20211213-232951).PNG">
<meta property="article:published_time" content="2022-05-25T14:20:14.000Z">
<meta property="article:modified_time" content="2022-05-25T15:01:38.557Z">
<meta property="article:author" content="莫伊">
<meta property="article:tag" content="Python">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://mooii.oss-cn-shanghai.aliyuncs.com/IMG_5370(20211213-232951).PNG"><link rel="shortcut icon" href="https://mooii.oss-cn-shanghai.aliyuncs.com/%E3%83%AA%E3%82%B9%E3%81%AE%E3%82%A2%E3%82%A4%E3%82%B3%E3%83%B3%E3%81%A7%E3%81%99%E3%81%9F%E3%81%84%E3%80%82.png"><link rel="canonical" href="https://mooii.gitee.io/2022/05/25/python05/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"简"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: false,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'python05-字典和集合',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-05-25 23:01:38'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/css/custom.css" media="defer" onload="this.media='all'"><!-- hexo injector head_end start --><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Zfour/Butterfly-swiper/swiper/swiper.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Zfour/Butterfly-swiper/swiper/swiperstyle.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Zfour/hexo-electric-clock@1.0.6/clock.css"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-clock/lib/clock.min.css" /><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/l-lin/font-awesome-animation/dist/font-awesome-animation.min.css" media="defer" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hexo-butterfly-tag-plugins-plus@latest/lib/tag_plugins.min.css" media="defer" onload="this.media='all'"><script async src="https://cdn.jsdelivr.net/npm/hexo-butterfly-tag-plugins-plus@latest/lib/carousel-touch.min.js"></script><!-- hexo injector head_end end --><meta name="generator" content="Hexo 5.4.0"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://portrait.gitee.com/uploads/avatars/user/1627/4881517_lolien_1621782146.png!avatar100" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">35</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">6</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">4</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 博文</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/comment/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://mooii.oss-cn-shanghai.aliyuncs.com/IMG_5370(20211213-232951).PNG')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">莫伊の测试笔记</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 博文</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/comment/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">python05-字典和集合</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-05-25T14:20:14.000Z" title="发表于 2022-05-25 22:20:14">2022-05-25</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-05-25T15:01:38.557Z" title="更新于 2022-05-25 23:01:38">2022-05-25</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Python/">Python</a></span></div><div class="meta-secondline"></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="概念"><a href="#概念" class="headerlink" title="概念"></a>概念</h1><ul>
<li>字典dict：由一系列键（key）和值（value）配对组成的元素的集合</li>
<li>集合set：没有键和值的配对，是一系列无序的、唯一的元素组合<h1 id="创建方式"><a href="#创建方式" class="headerlink" title="创建方式"></a>创建方式</h1></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">d1 = &#123;<span class="string">&#x27;name&#x27;</span>: <span class="string">&#x27;jason&#x27;</span>, <span class="string">&#x27;age&#x27;</span>: <span class="number">20</span>, <span class="string">&#x27;gender&#x27;</span>: <span class="string">&#x27;male&#x27;</span>&#125;</span><br><span class="line">d2 = <span class="built_in">dict</span>(&#123;<span class="string">&#x27;name&#x27;</span>: <span class="string">&#x27;jason&#x27;</span>, <span class="string">&#x27;age&#x27;</span>: <span class="number">20</span>, <span class="string">&#x27;gender&#x27;</span>: <span class="string">&#x27;male&#x27;</span>&#125;)</span><br><span class="line">d3 = <span class="built_in">dict</span>([(<span class="string">&#x27;name&#x27;</span>, <span class="string">&#x27;jason&#x27;</span>), (<span class="string">&#x27;age&#x27;</span>, <span class="number">20</span>), (<span class="string">&#x27;gender&#x27;</span>, <span class="string">&#x27;male&#x27;</span>)])</span><br><span class="line">d4 = <span class="built_in">dict</span>(name=<span class="string">&#x27;jason&#x27;</span>, age=<span class="number">20</span>, gender=<span class="string">&#x27;male&#x27;</span>) </span><br><span class="line">d1 == d2 == d3 ==d4</span><br><span class="line"><span class="literal">True</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">s1 = &#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>&#125;</span><br><span class="line">s2 = <span class="built_in">set</span>([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>])</span><br><span class="line">s1 == s2</span><br><span class="line"><span class="literal">True</span></span><br></pre></td></tr></table></figure>
<p>🎉ATTENTION：</p>
<ul>
<li>python中字典和集合的键和值都可以是混合类型（例如：s = {1,’hello’,5.0}）</li>
</ul>
<h1 id="元素访问方式"><a href="#元素访问方式" class="headerlink" title="元素访问方式"></a>元素访问方式</h1><blockquote>
<p>字典访问可以直接索引键，例如：</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">d = &#123;<span class="string">&#x27;name&#x27;</span>: <span class="string">&#x27;jason&#x27;</span>, <span class="string">&#x27;age&#x27;</span>: <span class="number">20</span>&#125;</span><br><span class="line"><span class="built_in">print</span>(d[<span class="string">&#x27;name&#x27;</span>])</span><br><span class="line"><span class="built_in">print</span>(d[<span class="string">&#x27;location&#x27;</span>])</span><br></pre></td></tr></table></figure>
<p>运行结果如下：</p>
<p><img src="https://mooii.oss-cn-shanghai.aliyuncs.com/20220525221505.png" alt=""></p>
<p>🎉ATTENTION：</p>
<ul>
<li>访问字典内不存在的元素会直接抛出异常</li>
</ul>
<p>也可以通过函数get(key,default)来进行索引，如果键不存在，调用get()函数可以返回一个默认值，例如：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">d = &#123;<span class="string">&#x27;name&#x27;</span>: <span class="string">&#x27;jason&#x27;</span>, <span class="string">&#x27;age&#x27;</span>: <span class="number">20</span>&#125;</span><br><span class="line"><span class="built_in">print</span>(d.get(<span class="string">&#x27;name&#x27;</span>))</span><br><span class="line"><span class="built_in">print</span>(d.get(<span class="string">&#x27;location&#x27;</span>, <span class="string">&#x27;这是自定义的默认值&#x27;</span>))</span><br></pre></td></tr></table></figure><br>运行结果如下：</p>
<p><img src="https://mooii.oss-cn-shanghai.aliyuncs.com/20220525221642.png" alt=""></p>
<p>🎉可以看出，返回的默认值为我们自定义的默认值</p>
<p>以上为字典内元素的访问方式，我们再来看看集合</p>
<p>🎉ATTENTION：</p>
<ul>
<li>集合不支持索引！！！</li>
<li>想要判断元素在不在集合内，可以用xx in dict/set来判断，参考下栗👇👇👇</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">s = &#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>&#125;</span><br><span class="line"><span class="built_in">print</span>(<span class="number">1</span> <span class="keyword">in</span> s)</span><br><span class="line"><span class="built_in">print</span>(<span class="number">10</span> <span class="keyword">in</span> s)</span><br></pre></td></tr></table></figure>
<p>运行结果：<br><img src="https://mooii.oss-cn-shanghai.aliyuncs.com/20220525221819.png" alt=""></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">d = &#123;<span class="string">&#x27;name&#x27;</span>: <span class="string">&#x27;jason&#x27;</span>, <span class="string">&#x27;age&#x27;</span>: <span class="number">20</span>&#125;</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;name&#x27;</span> <span class="keyword">in</span> d)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;location&#x27;</span> <span class="keyword">in</span> d)</span><br></pre></td></tr></table></figure>
<p>运行结果：</p>
<p><img src="https://mooii.oss-cn-shanghai.aliyuncs.com/20220525221947.png" alt=""></p>
<h1 id="元素操作"><a href="#元素操作" class="headerlink" title="元素操作"></a>元素操作</h1><h2 id="增、删、改"><a href="#增、删、改" class="headerlink" title="增、删、改"></a>增、删、改</h2><p>字典和集合都支持增加、删除、更新等操作<br>首先是字典，字典内对元素进行增加和更新，直接操作元素就可以了👇👇👇<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">d = &#123;<span class="string">&#x27;name&#x27;</span>: <span class="string">&#x27;mooii&#x27;</span>, <span class="string">&#x27;age&#x27;</span>: <span class="number">18</span>&#125;</span><br><span class="line">d[<span class="string">&#x27;gender&#x27;</span>] = <span class="string">&#x27;female&#x27;</span> <span class="comment"># 增加元素对&#x27;gender&#x27;: &#x27;female&#x27;</span></span><br><span class="line">d[<span class="string">&#x27;bir&#x27;</span>] = <span class="string">&#x27;2004-06-06&#x27;</span> <span class="comment"># 增加元素对&#x27;bir&#x27;: &#x27;2004-06-06&#x27;</span></span><br><span class="line"><span class="built_in">print</span>(d)</span><br><span class="line">d[<span class="string">&#x27;gender&#x27;</span>] = <span class="string">&#x27;male&#x27;</span> <span class="comment"># 更新键&#x27;gender&#x27;对应的值</span></span><br><span class="line"><span class="built_in">print</span>(d)</span><br><span class="line">d.pop(<span class="string">&#x27;gender&#x27;</span>) <span class="comment"># 删除键为&#x27;gender&#x27;的元素对</span></span><br><span class="line"><span class="built_in">print</span>(d)</span><br></pre></td></tr></table></figure></p>
<p>运行结果：</p>
<p><img src="https://mooii.oss-cn-shanghai.aliyuncs.com/20220525222052.png" alt=""></p>
<p>集合内对元素进行增加、更新、删除，参考栗子👇👇👇</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">s = &#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>&#125;</span><br><span class="line">s.add(<span class="number">4</span>) <span class="comment"># 增加元素4到集合</span></span><br><span class="line"><span class="built_in">print</span>(s)</span><br><span class="line">s.remove(<span class="number">4</span>) <span class="comment"># 从集合中删除元素4</span></span><br><span class="line"><span class="built_in">print</span>(s)</span><br></pre></td></tr></table></figure>
<p>运行结果如下：</p>
<p><img src="https://mooii.oss-cn-shanghai.aliyuncs.com/20220525222251.png" alt=""></p>
<p>🎉ATTENTION：</p>
<ul>
<li>集合的pop()操作删除的是集合内的最后一个元素，但是集合本身是无序的（也就是说，我们无法直观地知道会删除哪个元素），慎用pop操作！！！</li>
</ul>
<h2 id="排序"><a href="#排序" class="headerlink" title="排序"></a>排序</h2><p>对于字典的排序，我们可以根据键或值进行升序/降序操作，例如：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">d = &#123;<span class="string">&#x27;b&#x27;</span>: <span class="number">1</span>, <span class="string">&#x27;a&#x27;</span>: <span class="number">2</span>, <span class="string">&#x27;c&#x27;</span>: <span class="number">10</span>&#125;</span><br><span class="line">d_sorted_by_key = <span class="built_in">sorted</span>(d.items(), key=<span class="keyword">lambda</span> x: x[<span class="number">0</span>]) <span class="comment"># 根据字典键的升序排序</span></span><br><span class="line">d_sorted_by_value = <span class="built_in">sorted</span>(d.items(), key=<span class="keyword">lambda</span> x: x[<span class="number">1</span>]) <span class="comment"># 根据字典值的升序排序</span></span><br><span class="line"><span class="comment">## 运行结果</span></span><br><span class="line">d_sorted_by_key</span><br><span class="line">[(<span class="string">&#x27;a&#x27;</span>, <span class="number">2</span>), (<span class="string">&#x27;b&#x27;</span>, <span class="number">1</span>), (<span class="string">&#x27;c&#x27;</span>, <span class="number">10</span>)]</span><br><span class="line">d_sorted_by_value</span><br><span class="line">[(<span class="string">&#x27;b&#x27;</span>, <span class="number">1</span>), (<span class="string">&#x27;a&#x27;</span>, <span class="number">2</span>), (<span class="string">&#x27;c&#x27;</span>, <span class="number">10</span>)]</span><br></pre></td></tr></table></figure></p>
<p>🎉ATTENTION：</p>
<ul>
<li>字典进行排序操作后，返回的是一个列表，列表中的每个元素是由原字典的键和值组成的元组</li>
</ul>
<p>对于集合的排序，直接调用sorted()即可，返回的结果为排好序的列表，参考下例：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">s = &#123;<span class="number">3</span>, <span class="number">4</span>, <span class="number">2</span>, <span class="number">1</span>&#125;</span><br><span class="line"><span class="built_in">sorted</span>(s) <span class="comment"># 对集合的元素进行升序排序</span></span><br><span class="line"><span class="comment">#排序后的结果为</span></span><br><span class="line">[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>]</span><br></pre></td></tr></table></figure></article><div class="post-copyright"><div class="post-copyright__title"><span class="post-copyright-info"><h>python05-字典和集合</h></span></div><div class="post-copyright__type"><span class="post-copyright-info"><a href="https://mooii.gitee.io/2022/05/25/python05/">https://mooii.gitee.io/2022/05/25/python05/</a></span></div><div class="post-copyright-m"><div class="post-copyright-m-info"><div class="post-copyright-a"><h>作者</h><div class="post-copyright-cc-info"><h>莫伊</h></div></div><div class="post-copyright-c"><h>发布于</h><div class="post-copyright-cc-info"><h>2022-05-25</h></div></div><div class="post-copyright-u"><h>更新于</h><div class="post-copyright-cc-info"><h>2022-05-25</h></div></div><div class="post-copyright-c"><h>许可协议</h><div class="post-copyright-cc-info"><a class="icon" rel="noopener" target="_blank" title="Creative Commons" href="https://creativecommons.org/"><i class="fab fa-creative-commons"></i></a><a rel="noopener" target="_blank" title="CC BY-NC-SA 4.0" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a></div></div></div></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Python/">Python</a></div><div class="post_share"><div class="social-share" data-image="https://mooii.oss-cn-shanghai.aliyuncs.com/IMG_5370(20211213-232951).PNG" data-sites="weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://mooii.oss-cn-shanghai.aliyuncs.com/20211021204119.png" target="_blank"><img class="post-qr-code-img" src="https://mooii.oss-cn-shanghai.aliyuncs.com/20211021204119.png" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://mooii.oss-cn-shanghai.aliyuncs.com/20211021204141.png" target="_blank"><img class="post-qr-code-img" src="https://mooii.oss-cn-shanghai.aliyuncs.com/20211021204141.png" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2022/05/25/python06/"><img class="prev-cover" src="https://mooii.oss-cn-shanghai.aliyuncs.com/IMG_5373(20211213-233042).PNG" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">python06-输入与输出</div></div></a></div><div class="next-post pull-right"><a href="/2022/04/10/%E6%80%A7%E8%83%BD%E6%B5%8B%E8%AF%9501/"><img class="next-cover" src="https://mooii.oss-cn-shanghai.aliyuncs.com/IMG_5371(20211213-233011).PNG" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">性能测试01-性能测试中各种指标的关系</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://portrait.gitee.com/uploads/avatars/user/1627/4881517_lolien_1621782146.png!avatar100" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">莫伊</div><div class="author-info__description">幸运交给锦鲤，你只管努力就好</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">35</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">6</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">4</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/mooii"><i class="https://mooii.oss-cn-shanghai.aliyuncs.com/20211021164956.png"></i><span>我的主页</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">人生有限，接受事与愿违！！！</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%A6%82%E5%BF%B5"><span class="toc-number">1.</span> <span class="toc-text">概念</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E6%96%B9%E5%BC%8F"><span class="toc-number">2.</span> <span class="toc-text">创建方式</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%85%83%E7%B4%A0%E8%AE%BF%E9%97%AE%E6%96%B9%E5%BC%8F"><span class="toc-number">3.</span> <span class="toc-text">元素访问方式</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%85%83%E7%B4%A0%E6%93%8D%E4%BD%9C"><span class="toc-number">4.</span> <span class="toc-text">元素操作</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A2%9E%E3%80%81%E5%88%A0%E3%80%81%E6%94%B9"><span class="toc-number">4.1.</span> <span class="toc-text">增、删、改</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%8E%92%E5%BA%8F"><span class="toc-number">4.2.</span> <span class="toc-text">排序</span></a></li></ol></li></ol></div></div><div class="card-widget card-recommend-post"><div class="item-headline"><i class="fas fa-dharmachakra"></i><span>相关推荐</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2022/01/09/python01/" title="python01-字符串"><img src="https://mooii.oss-cn-shanghai.aliyuncs.com/IMG_5374(20211213-233104).PNG" alt="python01-字符串"></a><div class="content"><a class="title" href="/2022/01/09/python01/" title="python01-字符串">python01-字符串</a><time datetime="2022-01-09" title="发表于 2022-01-09">2022-01-09</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/01/09/python02/" title="python02-列表和元组"><img src="https://mooii.oss-cn-shanghai.aliyuncs.com/IMG_5373(20211213-233042).PNG" alt="python02-列表和元组"></a><div class="content"><a class="title" href="/2022/01/09/python02/" title="python02-列表和元组">python02-列表和元组</a><time datetime="2022-01-09" title="发表于 2022-01-09">2022-01-09</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/01/09/python03/" title="python03-字符串常用函数"><img src="https://mooii.oss-cn-shanghai.aliyuncs.com/IMG_5374(20211213-233104).PNG" alt="python03-字符串常用函数"></a><div class="content"><a class="title" href="/2022/01/09/python03/" title="python03-字符串常用函数">python03-字符串常用函数</a><time datetime="2022-01-09" title="发表于 2022-01-09">2022-01-09</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/01/09/python04/" title="python04-文件读取"><img src="https://mooii.oss-cn-shanghai.aliyuncs.com/IMG_5371(20211213-233011).PNG" alt="python04-文件读取"></a><div class="content"><a class="title" href="/2022/01/09/python04/" title="python04-文件读取">python04-文件读取</a><time datetime="2022-01-09" title="发表于 2022-01-09">2022-01-09</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/05/25/python06/" title="python06-输入与输出"><img src="https://mooii.oss-cn-shanghai.aliyuncs.com/IMG_5373(20211213-233042).PNG" alt="python06-输入与输出"></a><div class="content"><a class="title" href="/2022/05/25/python06/" title="python06-输入与输出">python06-输入与输出</a><time datetime="2022-05-25" title="发表于 2022-05-25">2022-05-25</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2021 - 2022 By 莫伊</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">好好学习🧡天天学习</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">简</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><div class="js-pjax"></div><script data-pjax defer src="/js/custom/fixed_card_widget.js"></script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-heart.min.js" async="async" mobile="false"></script><div id="fixedcard-dashboard"><button class="fixedcard-activebtn" type="button" title="用户信息" onclick="FixedCardWidget(&quot;class&quot;,&quot;card-info&quot;,&quot;0&quot;)"><i class="fas fa-address-book"></i></button><button class="fixedcard-activebtn" type="button" title="电子钟" onclick="FixedCardWidget(&quot;class&quot;,&quot;card-clock&quot;,&quot;0&quot;)"><i class="fas fa-cloud-sun"></i></button><button class="fixedcard-activebtn" type="button" title="相关推荐" onclick="FixedCardWidget(&quot;class&quot;,&quot;card-recommend-post&quot;,&quot;0&quot;)"><i class="fas fa-dharmachakra"></i></button><div class="fixedcard-user-avatar fixedcard-activebtn" onclick="RemoveFixedCardWidget()"><img class="fixedcard-user-avatar-img" src="https://portrait.gitee.com/uploads/avatars/user/1627/4881517_lolien_1621782146.png!avatar100" title="莫伊"></div></div></div><!-- hexo injector body_end start --> <script data-pjax>if(document.getElementById('recent-posts') && location.pathname =='/'){
    
    var parent = document.getElementById('recent-posts');
    var child = '<div class="recent-post-item" style="height: auto;width: 100%"><div class="blog-slider swiper-container-fade swiper-container-horizontal" id="swiper_container"><div class="blog-slider__wrp swiper-wrapper" style="transition-duration: 0ms"></div><div class="blog-slider__pagination swiper-pagination-clickable swiper-pagination-bullets"></div></div></div>';
    console.log('已挂载swiper')
    parent.insertAdjacentHTML("afterbegin",child)}
     </script>
<script data-pjax src="https://cdn.jsdelivr.net/gh/Zfour/Butterfly-swiper/swiper/swiper.min.js"></script>
<script data-pjax src="https://cdn.jsdelivr.net/gh/Zfour/Butterfly-swiper@0.18/swiper/swiperindex.js"></script>
<style></style><script data-pjax>function electric_clock_injector_config(){
                var parent_div_git = document.getElementsByClassName('sticky_layout')[0];
                var item_html = 'undefined';
                console.log('已挂载electric_clock')
                // parent_div_git.innerHTML=item_html+parent_div_git.innerHTML // 无报错，但不影响使用(支持pjax跳转)
                parent_div_git.insertAdjacentHTML("afterbegin",item_html) // 有报错，但不影响使用(支持pjax跳转)
            }if( document.getElementsByClassName('sticky_layout')[0] && (location.pathname ==='all'|| 'all' ==='all')){

            electric_clock_injector_config()
        } </script><script src="https://pv.sohu.com/cityjson?ie=utf-8"></script><script data-pjax  src="https://cdn.jsdelivr.net/gh/Zfour/hexo-electric-clock@1.0.6/clock.js"></script><script data-pjax>
  function butterfly_clock_injector_config(){
    var parent_div_git = document.getElementsByClassName('sticky_layout')[0];
    var item_html = '<div class="card-widget card-clock"><div class="card-glass"><div class="card-background"><div class="card-content"><div id="hexo_electric_clock"><img class="entered loading" id="card-clock-loading" src="https://npm.elemecdn.com/hexo-butterfly-clock/lib/loading.gif" style="height: 120px; width: 100%;" data-ll-status="loading"/></div></div></div></div></div>';
    console.log('已挂载butterfly_clock')
    parent_div_git.insertAdjacentHTML("afterbegin",item_html)
    }
  var elist = 'null'.split(',');
  var cpage = location.pathname;
  var epage = 'all';
  var flag = 0;

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_clock_injector_config();
  }
  else if (epage === cpage){
    butterfly_clock_injector_config();
  }
  </script><script src="https://pv.sohu.com/cityjson?ie=utf-8"></script><script data-pjax src="https://npm.elemecdn.com/hexo-butterfly-clock/lib/clock.min.js"></script><script async src="//at.alicdn.com/t/font_2032782_8d5kxvn09md.js"></script><!-- hexo injector body_end end --></body></html>